<template>
  <d-dialog
    ref="dialog"
    :header="isResetPwd ? '修改初始密码' : '修改密码'"
    api="system/tenant/profile/updatePwd"
    v-model:data="formData"
    v-model:visible="visible"
    :rules="rules"
    @success="handleSucc"
  >
    <t-form-item label="原来密码" name="oldPassword">
      <t-input
        type="password"
        v-model="formData.oldPassword"
        placeholder="请输入原来密码"
      ></t-input>
    </t-form-item>
    <t-form-item label="新密码" name="newPassword">
      <t-input type="password" v-model="formData.newPassword" placeholder="请输入新密码"></t-input>
    </t-form-item>
    <t-form-item label="确认密码" name="newPasswordPwd">
      <t-input
        type="password"
        v-model="formData.newPasswordPwd"
        placeholder="请输入新密码"
      ></t-input>
    </t-form-item>
  </d-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { removeToken, goLogin } from '@common'
const dialog = ref(null)
const visible = ref(false)
const isResetPwd = ref(false)
const INIT_STATUS = {
  oldPassword: '',
  newPassword: '',
  newPasswordPwd: ''
}
const formData = ref({
  ...INIT_STATUS
})
const rules = {
  oldPassword: [
    {
      required: true,
      message: '请输入原密码',
      trigger: 'blur'
    }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      message: '8-16位，必须包含大小写字母、数字',
      validator: (val) => {
        return (
          /\d/.test(val) &&
          /[a-z]/.test(val) &&
          /[A-Z]/.test(val) &&
          val.length >= 8 &&
          val.length <= 16
        )
      }
    },
    {
      message: '输入的字符不合法',
      validator: (val) => {
        const newVal = val.replace(/\d/g, '').replace(/[a-z]/gi, '')
        return !/[^!@#%&_]/.test(newVal)
      }
    }
  ],
  newPasswordPwd: [
    {
      required: true,
      message: '请确认新密码',
      trigger: 'blur'
    },
    {
      message: '两次输入密码不一致',
      validator: (val) => {
        return formData.value.newPassword == val
      }
    }
  ]
}

const show = (resetPwd) => {
  isResetPwd.value = resetPwd
  const obj = { ...INIT_STATUS, isEdit: true }
  formData.value = obj
  visible.value = true
}
const handleSucc = () => {
  removeToken()
  goLogin()
}
defineExpose({ show })
</script>
